#include<iostream>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<cstring>
#include<cerrno>
#include<cstdlib>
#include<cstdio>
#include<unistd.h>

#define PATHNAME "."
#define PROJ_ID 0x666
#define MAX_SIZE 4096

using namespace std;

key_t getkey()
{
    key_t key=ftok(PATHNAME,PROJ_ID);
    if(key<0)
    {
        cout<<errno<<":"<<strerror(errno)<<endl;
        exit(1);
    }
    return key;
}

int getshmhelper(key_t k,int falg)
{
    int shmid=shmget(k,MAX_SIZE,falg);
    if(shmid<0)
    {
        cout<<errno<<":"<<strerror(errno)<<endl;
        exit(2);
    }
    return shmid;
}

int getshm(key_t k)
{
    return getshmhelper(k,IPC_CREAT);
}

int creatshm(key_t k)
{
    return getshmhelper(k,IPC_CREAT|IPC_EXCL|0600);
}

void* attachshm(int shmid)//共享内存关联进程
{
    void* m=shmat(shmid,nullptr,0);
    if((long long)m==-1L)
    {
        cout<<errno<<":"<<strerror(errno)<<endl;
        exit(3);
    }
}

void dttachshm(void* start)//去关联
{
    if(shmdt(start)==-1)
    {
        cout<<errno<<":"<<strerror(errno)<<endl;
        exit(4);
    }
}

void deleteshm(int shmid)
{
    if(shmctl(shmid,IPC_RMID,nullptr)==-1)
    {
        cout<<errno<<":"<<strerror(errno)<<endl;
        exit(5);
    }
}